/**
 * @description formidable 封装
 * @author 印明帝
 */

const formidable = require('formidable')
const  http = require('http')
const  util = require('util')
const  path = require('path')
const  fse = require('fs-extra')
const { TEMP_PATH,MAX_FILE_SIZE } = require('../conf/file')



/**
 * 文件夹不存存在就创建创建文件夹
 * @method notDirDoCreateDir
 * @param {String} path 
 * @returns {Promise}
 */
async function notDirDoCreateDir(path) {
  try{
    // 先判断暂存文件夹是否存在
    let exist = await fse.pathExists(path)
    // 如果不存在就创建文件
    if(!exist) {
      fse.ensureDir(path)
    }
  } catch(err) {
    return Promise.resolve(err)
  }
}
// 尝试创建暂存目录
notDirDoCreateDir(TEMP_PATH)

/**
 * formidable 封装
 * @method customFormmid
 * @param {Object} ctx koa2ctx 
 * @returns {Function}
 */
function customFormmidable(ctx) {
  // 初始化
  const form = new formidable.IncomingForm() 
  // 文件保存目录
  form.uploadDir = TEMP_PATH
  // 扩展
  form.keepExtensions = true
  // 文件大小
  form.maxFileSize = MAX_FILE_SIZE
  // PROMISE
  const promise = new Promise((resolve,reject) => {
    form.parse(ctx.req, async (err, fields, files) => {
      // 出错
      if(err) {
        reject(err)
        return
      }
      // 把数据返回
      let data = files
      resolve(data)
    })
  })
  return promise
}
/**
 * 删除文件
 * @method removeFile
 * @param {String} path 
 */
async function removeFile(path) {
  try{
    let result = await fse.remove(path)
    return result
  } catch(e) {
    return Promise.resolve(e)
  }
}
/**
 * 移动文件
 * @method moveFile
 * @param {String} path 
 */
async function moveFile(srcPath,targetPath,filename) {
  try{
    let targetUrl = path.join(targetPath,filename)
    let result = await fse.move(srcPath,targetUrl)
    return result
  } catch(e) {
    return Promise.resolve(e)
  }
}
module.exports = {
  customFormmidable,
  notDirDoCreateDir,
  removeFile,
  moveFile
}